package com.ylbh.modules.business.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ylbh.common.pojo.business.dto.BusinessDetailsDTO;
import com.ylbh.common.pojo.business.dto.BusinessPicDTO;
import com.ylbh.common.pojo.business.dto.NoAdoptDTO;
import com.ylbh.common.pojo.business.dto.ToExamineDTO;
import com.ylbh.common.pojo.business.vo.GetUserInfoVO;
import com.ylbh.common.pojo.business.vo.ToExamineDetailsVO;
import com.ylbh.common.pojo.business.vo.ToExamineListVO;
import com.ylbh.common.pojo.finance.dto.*;
import com.ylbh.common.pojo.finance.vo.FinanceDetailsVO;
import com.ylbh.common.pojo.finance.vo.FinanceListVO;
import com.ylbh.common.utils.*;
import com.ylbh.modules.balancelog.entity.ShoppingBalanceLog;
import com.ylbh.modules.business.entity.ShoppingUserRevenueLog;
import com.ylbh.modules.business.entity.ShoppingUser;
import com.ylbh.modules.business.mapper.ShoppingUserMapper;
import com.ylbh.modules.business.service.ShoppingUserService;
import com.ylbh.modules.cashaudit.mapper.BusinessWithRecordMapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

@Service
@Transactional
public class ShoppingUserServiceImpl extends ServiceImpl<ShoppingUserMapper, ShoppingUser> implements ShoppingUserService {
    @Autowired
    private ShoppingUserMapper shoppingUserMapper;

    @Autowired
    private BusinessWithRecordMapper businessWithRecordMapper;

    private String shoppingMainImage = "http://image.yilianbaihui.cn/consumer/";

    @Value("${url.clearUser}")
    private String clearUser;

    @Value("${url.payFullSendType}")
    private String payFullSendType;

    /**
     * 联盟店审核列表
     * @param toExamineListDTO
     * @return
     */
    @Override
    public PageUtils queryBusinessList(ToExamineDTO toExamineListDTO) {
        Page<Object> page = new Page<>(toExamineListDTO.getPage(), toExamineListDTO.getLimit());

        List<ToExamineListVO> toExamineListVO = shoppingUserMapper.selectBusinessList(toExamineListDTO,page);
        Page<ToExamineListVO> page1 = new Page<>();
        page1.setRecords(toExamineListVO);
        page1.setTotal(page.getTotal());
        return new PageUtils(page1);
    }

    /**
     * 联盟店未审核数量
     * @return
     */
    @Override
    public int queryCount() {
       return shoppingUserMapper.selectCount();
    }

    /**
     * 允许联盟店通过审核
     * @param id
     */
    @Override
    public void modifyStatusById(Long id) {
        shoppingUserMapper.updateStatusById(id);
    }

    /**
     * 不允许联盟店通过审核
     * @param noAdopt
     */
    @Override
    public void modifyStatusByIds(NoAdoptDTO noAdopt) {
        shoppingUserMapper.updateStatusByIds(noAdopt);
    }

    /**
     * 批量删除
     * @param id
     */
    @Override
    public void removeBatchByIds(List<String> id) {
        shoppingUserMapper.deleteBatchIds(id);
    }

    /**
     * 根据id查询联盟店的详情
     * @param id
     * @return
     */
    @Override
    public ToExamineDetailsVO getBusinessUserById(Long id) {
        return shoppingUserMapper.selectBusinessUserById(id);
    }

    /**
     * 运营打款列表
     * @param financeListDTO
     * @return
     */
    @Override
    public PageUtils queryFinanceList(FinanceListDTO financeListDTO) {
        Page<Object> page = new Page<>(financeListDTO.getPage(), financeListDTO.getLimit());
        List<FinanceListVO> financeList = shoppingUserMapper.selectFinanceList(financeListDTO, page);
        Page<FinanceListVO> page1 = new Page<>();
        page1.setTotal(page.getTotal()).setRecords(financeList);
        return new PageUtils(page1);
    }

    /**
     * 运营打款详情
     * @param id
     * @return
     */
    @Override
    public FinanceDetailsVO getFinanceById(Long id) {
        FinanceDetailsVO finance = shoppingUserMapper.selectFinanceById(id);
        return finance;
    }

    /**
     * 修改商家详情
     * @param financeDetailsDTO
     */
    @Override
    public void modifyFinanceById(FinanceDetailsDTO financeDetailsDTO) {
        shoppingUserMapper.updateFinanceById(financeDetailsDTO);
    }

    /**
     * 给用户打款
     * @param financeDTO
     */
    @Override
    public String modifyMoneyById(FinanceDTO financeDTO) {
        if (null != financeDTO) {
            // 先查询出该用户的余额信息
            FinanceDetailsVO finance = shoppingUserMapper.selectFinanceById(financeDTO.getId());
            BigDecimal commissionMoney = finance.getCommissionMoney().subtract(financeDTO.getSendMoney());
            int money = commissionMoney.compareTo(new BigDecimal("0"));
            if (money == 0 || money == 1) {
                BigDecimal yesExtract = finance.getYesExtract().add(financeDTO.getSendMoney());
                // 修改用户的余额
                shoppingUserMapper.updateBalanceById(commissionMoney, yesExtract, financeDTO.getId());
            } else {
                return "当前用户余额不足打款金额";
            }
            try {
                // 清除redis缓存
                String cleanUserUrl = clearUser + finance.getId();
                URL url = new URL(cleanUserUrl);
                HttpURLConnection connection = (HttpURLConnection)url.openConnection();
                connection.connect();
            } catch (IOException e) {
                e.printStackTrace();
            }
            // 获取当前时间
            String date = DateHelper.getCurDateTime();
            String trxNo = DateHelper.getDateTime_IV(new Date());
            // 生成id
            IdWorker worker = new IdWorker();
            String withRecordId = worker.nextId();
            WithdrawalLogDTO logDTO = new WithdrawalLogDTO();
            logDTO.setDate(date);
            logDTO.setWithRecordId(withRecordId);
            logDTO.setSendMoney(financeDTO.getSendMoney());
            logDTO.setAccType(2);
            logDTO.setAccountNo(finance.getUsername());
            logDTO.setCashStatus(1);
            logDTO.setWithUserId(finance.getId());
            logDTO.setWithUserName(finance.getTrueName());
            logDTO.setUserType(finance.getUserTypes());
            logDTO.setWithPoundage(new BigDecimal(0.00));
            logDTO.setTrxNo(trxNo);
            logDTO.setWithSrc(3);
            logDTO.setCashRemarks("平台手动打款");
            // 新增提现日志
            shoppingUserMapper.insertLog(logDTO);

            // 打款新增用户余额变动表记录
            ShoppingBalanceLog balanceLog = new ShoppingBalanceLog();
            balanceLog.setBalanceId(worker.nextId());
            balanceLog.setCreateTime(new Date());
            balanceLog.setUserId(financeDTO.getId().intValue());
            balanceLog.setUserType(financeDTO.getUserTypes());
            balanceLog.setChangeType(8);
            balanceLog.setBalanceType(1);
            balanceLog.setPassiveUserId(ShiroUtils.getUserId().intValue());
            balanceLog.setChangeRemark("后台管理员对用户进行打款扣除佣金");
            balanceLog.setChangeBalance(financeDTO.getSendMoney());
            balanceLog.setUpdateUserId(ShiroUtils.getUserId().intValue());
            balanceLog.setUpdateTime(new Date());
            balanceLog.setState(1);
            balanceLog.setLogType(1);
            balanceLog.setCurrentBalance(commissionMoney);
            shoppingUserMapper.insertPaymentLog(balanceLog);

            // 系统日志
            String username = ShiroUtils.getUserEntity().getUsername();
            SystemLog log = new SystemLog();
            log.setUuid(UuidUtil.get32UUID());
            log.setUsername(username);
            log.setDate(date);
            log.setMsg("后台打款，提现id:"+finance.getId()+",打款金额:"+financeDTO.getSendMoney()+",时间:"+date);
            shoppingUserMapper.insertSystemLog(log);

            // 新增用户余额变动表记录
            // 创建人用户id
//            Long createUserId = ShiroUtils.getUserId();
//            int adminUserType = businessWithRecordMapper.selectAdminUserType(createUserId);
//            financeDTO.setDate(new Date());
//            shoppingUserMapper.insertBalanceLog(withRecordId,createUserId, adminUserType, financeDTO);
            return "打款成功";
        }
        return "打款失败";
    }

    /**
     * 批量审核
     * @param ids
     * @param batch
     */
    @Override
    public void modifyBatchByIds(List<String> ids, Integer batch) {
        shoppingUserMapper.updateBatchByIds(ids, batch);
    }

    /**
     * 根据id修改联盟店审核的详情
     * @param businessDetailsDTO
     */
    @Override
    public void modifyBusinessUserById(BusinessDetailsDTO businessDetailsDTO) {
        // 修改会员的主图
        if (null != businessDetailsDTO.getPhotoId()) {
            shoppingUserMapper.updateBusinessUserByPhotoId(businessDetailsDTO);
        } else  {
            // 如果用户还没主图，先插入一张图片并返回id，并放入到shopping_user表中photoId
            if (!StringUtils.isEmpty(businessDetailsDTO.getMainImgPath()) || !StringUtils.isEmpty(businessDetailsDTO.getMainImgName())) {
                BusinessPicDTO businessPicDTO = new BusinessPicDTO();
                businessPicDTO.setExt(businessDetailsDTO.getMainImgName().substring(businessDetailsDTO.getMainImgName().lastIndexOf(".") + 1));
                businessPicDTO.setPath(businessDetailsDTO.getMainImgPath());
                businessPicDTO.setName(businessDetailsDTO.getMainImgName());
                businessPicDTO.setDate(new Date());
                shoppingUserMapper.insertPic(businessPicDTO);
                businessDetailsDTO.setPhotoId(businessPicDTO.getId());
            }
        }
        shoppingUserMapper.updateBusinessUserById(businessDetailsDTO);
    }

    /**
     * 修改联盟店的满送类型
     * @param id
     * @param payFullSendType
     * @return
     */
    @Override
    public String modifyPayFullSendById(Long id, Integer payFullSendType) {
        if(null != id) {
            // 在修改满减前，先去查询这个商家是否还有订单是未完成状态
            int count = shoppingUserMapper.selectOrderStatusById(id);
            if (count > 0)
                return "{\"code\":500,\"message\":\"该商家还有订单未完成\"}";
        }
        HashMap<String, String> map = new HashMap<>();
        map.put("userId", id.toString());
        map.put("payFullSendType", payFullSendType.toString());
        return HttpClientHelperUtils.sendHttpPost(this.payFullSendType, map);
    }

    @Override
    public boolean updateIntegral(String userName, String id, Integer integral) {
        try {
            shoppingUserMapper.inUserName(userName,integral);
            shoppingUserMapper.outYlbh(id,integral);
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            return false;
        }
        return true;
    }

    @Override
    public GetUserInfoVO getUserInfoByUserName(String userName) {
        return shoppingUserMapper.selectUserByUserName(userName);
    }

    @Override
    public void updateLog(GetUserInfoVO userVo, String ylbhId, Integer integral) {
        try {
            ShoppingUserRevenueLog logEntity1 = getLogInfo(userVo,integral);
            logEntity1.setUserId(userVo.getId());
            logEntity1.setType(0);
            logEntity1.setFromUserId(ylbhId);
            shoppingUserMapper.insertRevenueLog(logEntity1);
            ShoppingUserRevenueLog logEntity2 = getLogInfo(userVo,integral);
            logEntity2.setUserId(ylbhId);
            logEntity2.setType(1);
            logEntity2.setFromUserId(userVo.getId());
            shoppingUserMapper.insertRevenueLog(logEntity2);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static ShoppingUserRevenueLog getLogInfo(GetUserInfoVO userVo,Integer integral){
        ShoppingUserRevenueLog logEntity = new ShoppingUserRevenueLog ();
        logEntity.setAddTime(new Date());
        logEntity.setDeleteStatus(0);
        logEntity.setIntegral(integral);
        logEntity.setRemark(userVo.getRemark());
        logEntity.setFromType(2);
        logEntity.setOperatingPlatform("1");
        logEntity.setCurrentIntegral(userVo.getIntegral());
        return logEntity;
    }
}
